package com.my;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * Created by YJH on 2017/7/13 10:38.
 */
public class AuthorityFilter extends HttpFilter {

    @Override
    public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        //获取ServletPath
        String servletPath = request.getServletPath();

        //不需要连接的url列表
        List<String> uncheckedUrls = Arrays.asList("/403.jsp", "/articles.jsp", "/authority-manager.jsp", "/login.jsp", "logout.jsp");
        if (uncheckedUrls.contains(servletPath)) {
            filterChain.doFilter(request, response);
            return;
        }

        //在用户已经登录的情况下，获取用户信息。session.getAttribute("user")
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }

        //在获取用户所具有的权限的信息：List<Authority>
        List<Authority> authorityList = user.getAuthorityList();

        //检验用户是否有请求ServletPath的权限
        Authority authority = new Authority(null, servletPath);
        //若有权限则：响应
        if (authorityList.contains(authority)) {
            filterChain.doFilter(request, response);
            return;
        }

        //若没有权限：重定向到403.jsp
        response.sendRedirect(request.getContextPath() + "/403.jsp");
    }
}
